package com.example.online_chat.api;

import com.example.online_chat.component.OnlineUserManager;
import com.example.online_chat.model.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.List;

@Component
public class WebSockAPI extends TextWebSocketHandler {
    @Autowired
    private OnlineUserManager onlineUserManager;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private MessageSessionMapper messageSessionMapper;

    @Autowired
    private FriendReqMapper friendReqMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("[WebSocketAPI] 连接成功");
        User user = (User) session.getAttributes().get("user");
        if (user == null) {
            return;
        }

        onlineUserManager.online(user.getUserId(), session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("[WebSocketAPI] 收到消息: " + message.toString());

        MessageRequest request = objectMapper.readValue(message.getPayload(), MessageRequest.class);
        switch (request.getType()) {
            case "message":
                // 先获取到当前用户的信息, 后续要进行消息转发啥的
                User user = (User) session.getAttributes().get("user");
                if (user == null) {
                    System.out.println("[WebSocketAPI -> handleTextMessage] user == null! 未登录用户, 无法进行消息转发");
                    return;
                }
                // 进行消息转发
                transferMessage(user, request);
                break;
            case "friendRequest":
                // 进行好友申请转发
                transferFriendRequest(request);
                break;
            case "acceptFriendRequest":
                // 接受好友请求
                transferAcceptRequest(request);
                break;
            default:
                System.out.println("[WebSocketAPI -> handleTextMessage] req.type 有误! " + message.getPayload());
                break;
                
        }
    }

    private void transferAcceptRequest(MessageRequest request) throws IOException {
        WebSocketSession session = onlineUserManager.getSession(request.getRequestId());
        MessageResponse response = new MessageResponse();
        response.setType("acceptFriendRequest");

        String respJson = objectMapper.writeValueAsString(response);
        if (session != null) {
            session.sendMessage(new TextMessage(respJson));
        }
    }

    private void transferFriendRequest(MessageRequest request) throws IOException {
        int receiverId =
                friendReqMapper.getUserIdByName(request.getReceiver());
        WebSocketSession session = onlineUserManager.getSession(receiverId);

        MessageResponse response = new MessageResponse();
        response.setType("friendRequest");

        String respJson = objectMapper.writeValueAsString(response);
        if (session != null) {
            session.sendMessage(new TextMessage(respJson));
        }
    }

    private void transferMessage(User user, MessageRequest request) throws IOException {
        // 构造要发送的对象
        MessageResponse response = new MessageResponse();
        response.setType("message");
        response.setFromId(user.getUserId());
        response.setFromName(user.getUsername());
        response.setSessionId(request.getSessionId());
        response.setContent(request.getContent());

        // 把这个对象转换成 json 字符串
        String respJson = objectMapper.writeValueAsString(response);
        System.out.println("[WebSocketAPI -> transferMessage] respJson: " + respJson);

        // 根据 sessionId 来查找里面对应的用户
        List<Friend> friends =
                messageSessionMapper.getFriendsBySessionId(request.getSessionId(), user.getUserId());
        // 把自己也添加进去
        Friend myself = new Friend();
        myself.setFriendId(user.getUserId());
        myself.setFriendName(user.getUsername());

        friends.add(myself);

        for (Friend friend : friends) {
            WebSocketSession session =
                    onlineUserManager.getSession(friend.getFriendId());
            if (session == null) {
                // 当前用户不在线
                continue;
            }

            session.sendMessage(new TextMessage(respJson));
        }

        // 将消息添加到数据库
        Message message = new Message();
        message.setFromId(user.getUserId());
        message.setSessionId(request.getSessionId());
        message.setContent(request.getContent());
        messageMapper.add(message);

        messageSessionMapper.updateLastTime(request.getSessionId());
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("[WebSocketAPI] 连接异常: " + exception.toString());
        User user = (User) session.getAttributes().get("user");
        if (user != null) {
            onlineUserManager.offline(user.getUserId(), session);
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("[WebSocketAPI] 连接关闭: " + status.toString());
        User user = (User) session.getAttributes().get("user");
        if (user != null) {
            onlineUserManager.offline(user.getUserId(), session);
        }
    }
}
